<?php
/**
 * Created by PhpStorm.
 * User: zhao
 * Date: 2018/5/3
 * Time: 17:15
 */

namespace App\Handlers;

use Overtrue\EasySms\Exceptions\Exception;
use Cache;

class SendSmsHandler extends BaseHandle
{
    const SAVE_TIME = 5;//m
    /**
     * @param $phone
     * @param $data
     * @return bool
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function send($phone,$data,$code='')
    {

        if(env('APP_DEBUG')){
            Cache::set($this->getKey($data['template'],$phone),$code,self::SAVE_TIME);

            return true;
        }else{
            try{

                $result = app('easysms')->send($phone,$data);

                if(isset($result['aliyun']['status']) && $result['aliyun']['status']==='success') {

                    if(!empty($code)) Cache::set($this->getKey($data['template'],$phone),$code,self::SAVE_TIME);

                    return true;
                }

                $this->_log(['message'=>"(1)".var_export(get_object_vars($result['aliyun']),1)],'sms_error');

                return false;

            }catch (Exception $e){

                $result = $e->results ;

                $res = isset($result['aliyun']['exception'])??'未知';

                $this->_log(['message'=>"(2)".var_export(get_object_vars($result['aliyun']['exception']).'request_data:'.json_encode($data),1)],'sms_error');

                return false;
            }
        }


    }

    /**
     * @param $templete_id模板ID
     * @param $phone 手机号
     * @param $code 验证码
     * @return array
     */
    public function validateCode(string $templete_id,$phone,$code)
    {
        $cache_key = $this->getKey($templete_id,$phone);

        $save_code = Cache::get($cache_key);

        if(empty($save_code)) return ['code'=>422,'msg'=>'验证码已过期'];

        if(!hash_equals("$save_code","$code")) return ['code'=>401,'msg'=>'验证码错误'];

        // 清除验证码缓存
        Cache::forget($cache_key);

        return ['code'=>200,'msg'=>'验证成功'];
    }

    protected function getKey($temple_id,$phone)
    {
        return md5($temple_id.$phone);
    }

}